package com.yu.waterstation.system.common.interceptor;

import com.yu.waterstation.common.common.annotation.NeedPermission;
import com.yu.waterstation.common.common.constant.Const;
import com.yu.waterstation.common.common.exception.ServiceException;
import com.yu.waterstation.common.common.util.jwt.JWTUtil;
import com.yu.waterstation.system.common.util.session.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 系统后台api拦截器
 */
@Slf4j
@Component
public class SystemApiInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ((handler instanceof HandlerMethod)) {
            NeedPermission needPermission = ((HandlerMethod) handler).getMethod().getAnnotation(NeedPermission.class);
            if (needPermission == null)
                return super.preHandle(request, response, handler);

            String token = SessionUtil.getToken(request); // 检测token的有效性
            if (StringUtils.isEmpty(token) || !JWTUtil.verify(token))
                throw ServiceException.CONST_token_is_not_validate;

            // 检验是否登录
            Integer sysUserId = JWTUtil.getUserId(token);
            if (sysUserId == null || !SessionUtil.checkSysUserLogin(sysUserId))
                throw ServiceException.CONST_user_not_login;

            // 检验权限
            if (!SessionUtil.hasPermission(needPermission.value(), SessionUtil.getCurrentSysUserDTO(sysUserId).getPermissions()))
                throw ServiceException.CONST_not_authorized;

            request.setAttribute(Const.CONST_sys_user_id, sysUserId);
            request.setAttribute(Const.CONST_username, JWTUtil.getUsername(token));
        }
        return super.preHandle(request, response, handler);
    }

}
